<template>
  <a-modal
    title="調整租金"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :footer="[]"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['qsNum']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['rentStartDate']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['rentEndDate']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['rent']" /></a-form-item>
        <a-form-item
          label="租金調整"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-radio-group v-decorator="['adjustType', { initialValue: 2 }]" @change="onAdjustTypeChange">
            <a-radio-button :value="2">
              漲
            </a-radio-button>
            <a-radio-button :value="3">
              降
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="租金方式"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-radio-group v-decorator="['adjustStyle', { initialValue: 1 }]" @change="onAdjustStyleChange">
            <a-radio-button :value="1">
              金額
            </a-radio-button>
            <a-radio-button :value="2">
              百分比
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="調整值"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input-number
              style="width:100%"
              placeholder="請輸入調整值"
              :precision="2"
              :min="0"
              :max="99999999"
              :step="10"
              v-decorator="['changeMoney', { initialValue: 0, rules: [{required: true, message: '請輸入調整值'}]}]"
              @change="onRentChange"/>
        </a-form-item>
        <a-form-item
          label="調整爲"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input-number
              style="width:100%"
              :precision="2"
              :min="0"
              :max="99999999"
              :step="10"
              v-decorator="['rentWe', { initialValue: 0 }]"
              :disabled="true"
              @change="onRentChange"/>
        </a-form-item>
         <a-form-item
                label="生效賬單"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
              <a-input placeholder="生效賬單" :disabled="true"  v-decorator="['name', {rules: [{ required: true, message: '請選擇生效賬單！' }]}]">
                <a-icon slot="addonAfter" type="search" @click="onSelectBill"/>
              </a-input>
        </a-form-item>
      </a-form>
      <a-row class="but">
        <a-button  type="primary" @click="handleSubmit">確定</a-button>
      </a-row>
      <a-divider />
      <a-table
              size="middle"
              :columns="columns"
              :dataSource="adjustDataList"
              :pagination="false"
              :rowKey="(record) => record.id"
              :loading="memberLoading">
              <template slot="adjustType" slot-scope="text">
                 {{ adjustmentTypeFilter(text) }}
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm v-if="record.adjustType !== 1" placement="topRight" title="确认删除？" @confirm="() => delAdjust(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
      </a-table>
    </a-spin>
    <bill-plan-select ref="billPlanSelect" @ok="handleSelectBillOk" />
  </a-modal>
</template>

<script>
  import moment from 'moment'
  import { getAdjustmentListByLeaseId, addAdjustmentList, delAdjustById } from '@/api/modular/main/houselease/houseLeaseManage'
  import billPlanSelect from './billPlanSelect.vue'
  export default {
    components: {
      billPlanSelect
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        memberLoading: false,
        form: this.$form.createForm(this),
        leaseId: 0,
        adjustDataList: [],
        columns: [
          {
            title: '生效賬單',
            dataIndex: 'name',
            width: '30%',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '調整方式',
            dataIndex: 'adjustType',
            width: '15%',
            scopedSlots: { customRender: 'adjustType' }
          },
          {
            title: '調整值',
            dataIndex: 'changeMoney',
            width: '15%',
            scopedSlots: { customRender: 'changeMoney' }
          },
          {
            title: '調整爲',
            dataIndex: 'rent',
            width: '20%',
            scopedSlots: { customRender: 'rent' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        adjustmentTypeDic: [ { id: 1, name: '簽約' }, { id: 2, name: '漲租' }, { id: 3, name: '降租' } ]
      }
    },
    methods: {
      moment,
      // 初始化方法
      edit (record) {
        this.visible = true
        this.leaseId = record.id
        this.initNeedData(this.leaseId)
        setTimeout(() => {
          this.form.setFieldsValue(
            {
              rent: record.rent
            }
          )
        }, 100)
      },
      initNeedData(leaseId) {
        getAdjustmentListByLeaseId(leaseId).then((res) => {
          if (res.code === 200) {
            this.adjustDataList = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      adjustmentTypeFilter (id) {
        // eslint-disable-next-line eqeqeq
        const values = this.adjustmentTypeDic.filter(item => item.id == id)
        if (values.length > 0) {
          return values[0].name
        }
      },
       onAdjustTypeChange(e) {
        const adjustType = e.target.value
        const rent = this.form.getFieldValue('rent')
        const changeMoney = this.form.getFieldValue('changeMoney')
        const adjustStyle = this.form.getFieldValue('adjustStyle')
        this.makeAmount(adjustType, rent, changeMoney, adjustStyle)
      },
      onAdjustStyleChange(e) {
        const adjustStyle = e.target.value
        const adjustType = this.form.getFieldValue('adjustType')
        const rent = this.form.getFieldValue('rent')
        const changeMoney = this.form.getFieldValue('changeMoney')
        this.makeAmount(adjustType, rent, changeMoney, adjustStyle)
      },
      onRentChange(e) {
        const adjustType = this.form.getFieldValue('adjustType')
        const rent = this.form.getFieldValue('rent')
        const adjustStyle = this.form.getFieldValue('adjustStyle')
        const changeMoney = e
        this.makeAmount(adjustType, rent, changeMoney, adjustStyle)
      },
      makeAmount(adjustType, rent, changeMoney, adjustStyle) {
        var rentPrice = 0
        if (adjustType === 2) {
          if (adjustStyle === 1) {
            rentPrice = rent + changeMoney
          } else {
            rentPrice = rent + rent * (changeMoney / 100)
          }
        } else {
          if (adjustStyle === 1) {
            rentPrice = rent - changeMoney
          } else {
            rentPrice = rent - rent * (changeMoney / 100)
          }
        }
        if (rentPrice < 0) {
          this.$message.error('調整後的租金不能小於0')
          return
        }
        this.$nextTick(() => {
            this.form.setFieldsValue({
              rentWe: rentPrice
            })
        })
      },
      onSelectBill() {
       this.$refs.billPlanSelect.select(this.leaseId, '')
      },
      handleSelectBillOk(item) {
        this.$nextTick(() => {
            this.form.setFieldsValue({
              qsNum: item.qsNum,
              name: item.name,
              rentStartDate: item.rentStartDate,
              rentEndDate: item.rentEndDate
            })
        })
      },
      delAdjust(id) {
        this.confirmLoading = true
        delAdjustById(id).then((res) => {
          if (res.code === 200) {
            this.initNeedData(this.leaseId)
          } else {
            this.$message.error(res.msg)
          }
        }).finally((res) => {
          this.confirmLoading = false
        })
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            if (values.changeMoney <= 0) {
               this.$message.error('調整值金額需大於0')
               this.confirmLoading = false
               return false
            }
            if (values.rent < 0) {
               this.$message.error('調整後的金額不能小於0')
               this.confirmLoading = false
               return false
            }
            values.leaseId = this.leaseId
            addAdjustmentList(values).then((res) => {
              if (res.code === 200) {
                this.$message.success('添加成功！')
                this.confirmLoading = false
                this.initNeedData(this.leaseId)
              } else {
                this.$message.error(res.msg)//  + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.leaseId = 0
      }
    }
  }
</script>

<style scoped>
.title-it{
  background-color: aquamarine;
  padding: 10px 0px;
}
.mocheck{
  background-color: rgba(58, 136, 180, 0.822);
  color: aliceblue;
}
.but{
  text-align: center;
}
</style>
